import Wechat, { OfficialAccountService } from "../sdk/lib";
import axios from "axios";
import * as https from "https";
import * as qs from "querystring";
// import msgHandler from "./messageHandler";

const ax = axios.create({
    timeout: 60000,
    withCredentials: false,
    httpsAgent: new https.Agent({
        rejectUnauthorized: false
    }),
    headers: {
        Accept: "*/*"
    }
});

export default function(wx, app) {
    const wxServer = wx.getService("server") as OfficialAccountService.ServerService;

    wxServer.handle(async function handler(msg) {
        if (msg.content === "image") {
            return new Wechat.Core.ImageReply(
                "XjUGEEovVNPn7rm_g8Nk_U_cf1gz8jVS6-u1CqNfB5qr24W9PVpI7q2B7qQZa7eb" // "JhDXmPhUG8TOZQTZgoKeL7hDcyRO-IK_m3QtOluwFHnUq8u6SCtF55718Ka9dKBq"
            );
        } else if (msg.content === "ip") {
            const base = wx.getService("base");
            try {
                const ips = await base.getValidIps();
                return ips.join(";");
            } catch (error) {
                return error.message || error.toString();
            }
        } else if (msg.content === "upload") {
            const media = wx.getService("media");
            try {
                const timer = setTimeout(() => {
                    return "upload timeout";
                }, 4000);
                const result = await media.uploadImage("/home/wwwroot/wx/test/test.jpg");
                console.log(result);
                clearTimeout(timer);
                return result;
            } catch (error) {
                return error.message || error.toString();
            }
        } else if (msg.content === "menu-list") {
            const menu = wx.getService("menu");
            try {
                const result = await menu.list();
                return JSON.stringify(result);
            } catch (error) {
                return error.message || error.toString();
            }
        } else if (msg.content === "menu-create") {
            const menu = wx.getService("menu");
            try {
                const result = await menu.create([
                    {
                        type: "click",
                        name: "菜单1",
                        key: "main1",
                        sub_button: [
                            {
                                type: "view",
                                name: "WebApproach",
                                url: "https://webapproach.net"
                            },
                            {
                                type: "view",
                                name: "Tint",
                                url: "https://webapproach.net/tag/tinection"
                            }
                        ]
                    },
                    {
                        type: "view",
                        name: "WebApproach",
                        url: "https://webapproach.net"
                    },
                    {
                        type: "view",
                        name: "Github",
                        url: "https://github.com/thundernet8"
                    }
                ]);
                return JSON.stringify(result);
            } catch (error) {
                return error.message || error.toString();
            }
        } else if (msg.content === "menu-delete") {
            const menu = wx.getService("menu");
            try {
                const result = await menu.delete();
                return JSON.stringify(result);
            } catch (error) {
                return error.message || error.toString();
            }
        } else if (msg.content === "user-list") {
            const user = wx.getService("user");
            try {
                const result = await user.list();
                return JSON.stringify(result);
            } catch (error) {
                return error.message || error.toString();
            }
        } else if (msg.content && /([0-9]{16})/i.test(msg.content)) {
            const match = msg.content.match(/([0-9]{16})/i);
            try {
                const result = await ax
                    .post(
                        "https://webapproach.net/tint/query.php",
                        qs.stringify({
                            order: match![1],
                            o: msg.content.endsWith("o") || msg.content.endsWith("O") ? 1 : null,
                            u: msg.content.endsWith("u") || msg.content.endsWith("U") ? 1 : null
                        })
                    )
                    .then(resp => resp.data);
                return Object.keys(result)
                    .map(key => `${key}: ${result[key]}`)
                    .join("\r\n");
            } catch (error) {
                return error.message || error.toString();
            }
        }
        return "received: " + (msg.content || "no content");
    });

    // app.use(xmlParser());
    wxServer.connect(app);
    // app.use(wxServer.middleware);
}
